package com.franklin.validation.core.argument.impl.string;

import com.franklin.validation.core.annotations.ParamCheck;
import com.franklin.validation.core.annotations.Resolver;
import com.franklin.validation.core.annotations.WebFluxFormDataComponent;
import com.franklin.validation.core.entity.CheckFormEntity;
import com.franklin.validation.core.utils.DataCheckUtil;
import com.franklin.validation.core.utils.ReflectionUtil;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Description :
 * Create By: Franklin
 * Date : 2020/6/15 16:27
 */
@Resolver
@WebFluxFormDataComponent
public class NumberResolverResult extends AbstractStringResolverResult<Number> {

    @Override
    public boolean checkSize(CheckFormEntity input) {
        ParamCheck paramCheck = input.getParamCheck();
        String value = this.getStringValue(input.getValues());
        if (DataCheckUtil.isEmpty(value)){
            return false;
        }
        int i = new BigDecimal(value).intValue();
        return paramCheck.max() >= i && paramCheck.min() <= i;
    }

    @Override
    public Number onError(CheckFormEntity input) {
        ParamCheck paramCheck = input.getParamCheck();
        if (!ReflectionUtil.isSystemDefaultValue(paramCheck.defaultValue())){
            return this.getNumber(input.getParamType(),paramCheck.defaultValue());
        }
        return this.getNumber(input.getParamType(),"0");
    }

    private Number getNumber(Class<?> type,String valueString) {
        if (DataCheckUtil.isEmpty(valueString)){
            valueString = "0";
        }
        if (type == Long.class || type == long.class){
            return new Long(valueString);
        }else if (type == Integer.class || type == int.class){
            return new Integer(valueString);
        }else if (type == Double.class || type == double.class){
            return new Double(valueString);
        }else if (type == BigDecimal.class){
            return new BigDecimal(valueString);
        }
        return 0;
    }

    @Override
    public Number getResult(CheckFormEntity input) {
        return this.getNumber(input.getParamType(),this.getStringValue(input.getValues()));
    }

}
